package com.widetrust.carpro.orm;

import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.jdbc.core.RowMapper;

/**
 * @author yyq
 *
 */
public class RowMapperForSpringJDBC implements RowMapper {
	private Class domainClass=null;
	
	public RowMapperForSpringJDBC(String classpath){
		try {
			domainClass = Class.forName(classpath);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public RowMapperForSpringJDBC(Class domainClass) {
		this.domainClass=domainClass;
	}

	public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
		try {
			Object domain=domainClass.newInstance();
			String propertyName;
			String propertyTypeName;
			PropertyDescriptor[] propertyDescriptors=PropertyUtils.getPropertyDescriptors(domainClass);
			for(int i=0;i<propertyDescriptors.length;i++){
				PropertyDescriptor pd=propertyDescriptors[i];
				propertyName=pd.getName();
				propertyTypeName=pd.getPropertyType().getName();
				
				try{
					if("java.lang.String".equals(propertyTypeName)){
						if(rs.getString(propertyName)!=null)
						PropertyUtils.setProperty(domain,propertyName,rs.getString(propertyName));
					}else if("int".equals(propertyTypeName)){
						PropertyUtils.setProperty(domain,propertyName,rs.getInt(propertyName));
					}else if("boolean".equals(propertyTypeName)){
						PropertyUtils.setProperty(domain,propertyName,rs.getBoolean(propertyName));
					}else if("double".equals(propertyTypeName)){
						PropertyUtils.setProperty(domain,propertyName,rs.getDouble(propertyName));
					}else if("long".equals(propertyTypeName)){
						PropertyUtils.setProperty(domain,propertyName,rs.getLong(propertyName));
					}else if("java.sql.Date".equals(propertyTypeName)){
						PropertyUtils.setProperty(domain,propertyName,rs.getDate(propertyName));
					}else if("float".equals(propertyTypeName)){
						PropertyUtils.setProperty(domain,propertyName,rs.getFloat(propertyName));
					}else if("java.math.BigDecimal".equals(propertyTypeName)){
						PropertyUtils.setProperty(domain,propertyName,rs.getBigDecimal(propertyName));
					}else if("byte".equals(propertyTypeName)){
						PropertyUtils.setProperty(domain,propertyName,rs.getByte(propertyName));
					}else if("java.sql.Clob".equals(propertyTypeName)){
						PropertyUtils.setProperty(domain,propertyName,rs.getClob(propertyName));
					}else if("java.sql.Time".equals(propertyTypeName)){
						PropertyUtils.setProperty(domain,propertyName,rs.getTime(propertyName));
					}
				}catch(java.sql.SQLException e){
					continue;
				}
			}
			
			return domain;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
